package api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import domain.User;
import exception.LoginException;
import service.UserService;
import utils.GetRequestJsonUtils;
import utils.Response;
import utils.ResponseCode;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;

public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       //第一步提取参数
        JSONObject object= GetRequestJsonUtils.getRequestJsonObject(req);
        String user_str=object.getString("user");
        //第二步转换参数成user对象
        User user= JSON.parseObject(user_str,User.class);
        //第三步去查询数据库表中是否有这个记录
        UserService userService=new UserService();
        Response build= null;
        try {
            userService.login(user);
            //创建一个Session,该session对象是这个请求浏览器独有
            HttpSession session= req.getSession();
            session.setAttribute("user",user);
            Cookie cookie=new Cookie("JSESSIONID",session.getId());
            resp.addCookie(cookie);
            build=Response.build(ResponseCode.SUCCESS);

        }catch (LoginException e){
            e.printStackTrace();
             build=Response.build(e.getError());
        //判断为空，生成登录失败消息对象
        //把消息对象转换成字符串，返回浏览器；
        }
        resp.setContentType("text/html;charset=utf-8");
        resp.getWriter().write(JSON.toJSON(build).toString());
    }
}
